#!/usr/bin/lua -f
s=arg[0] while strsub(s,-1)~="/" do s=strsub(s,1,-2) end dofile(s.."common.lua")
_ALERT("Starting dhcpcd--\n")
if arg[1]==nil then
 IF="eth0"
else
 IF=arg[1]
end
blen=240
glops={}
BOOTREPLY="\2" PAD="\0" END="\255" MASK="\1" GW="\3" DNS="\6" CNM="\12"
DMN="\15" RIP="\50" MSG="\53" DISCOVER="\1" OFFER="\2" REQUEST="\3"
ACK="\5" SRV="\54" REQ="\55" ERR="\56" CID="\61" FLAGS="\128\0"
function parse(s)
	x=1
	while 1 do
		opt=strsub(s,x,x)
		x=x+1
		if opt==END then break end
		if opt~=PAD then
			len=strbyte(strsub(s,x,x))
			x=x+1
			glops[opt]=strsub(s,x,x+len-1)
			x=x+len
		end
	end
end
function toopt()
	local s=""
	for a,b in glops do
		s=s..a..strchar(strlen(b))..b
	end
	return s..END
end
function todots(s)
	s=glops[s]
	return		
	 strbyte(strsub(s,1,1)).."."..
	 strbyte(strsub(s,2,2)).."."..
	 strbyte(strsub(s,3,3))..".".. 
	 strbyte(strsub(s,4,4)) 
end
check({z=1},execute("ifconfig "..IF.." 1.1.1.1 broadcast 255.255.255.255 netmask 255.0.0.0 up"))
check({z=1},execute("route add default "..IF))
readfrom("|ifconfig "..IF.."|grep HWaddr")
HW=read()
x=strfind(HW,"HWaddr")
hw="" for i=x+7,x+22,3 do
	hw=hw..strchar(tonumber(strsub(HW,i,i+1),16))
end
sockO=udpsocket({SO_BROADCAST=1})
sockI=udpsocket()
sockI:timeout(5)
check({v=1},sockI:setsockname("0.0.0.0",68))
check({v=1},sockO:setsockname("0.0.0.0",68))
check({v=1},sockO:setpeername("255.255.255.255",67))
body=	"\1\1\6\0"
	..strrep(strchar(random(0,255))..strchar(random(0,255)),2)
	.."\0\0"..FLAGS
	..strrep("\0",16)..hw..strrep("\0",202).."\99\130\83\99"
glops[MSG]=DISCOVER
glops[CID]="\1"..hw
glops[CNM]="tomsrtbt\0"
glops[REQ]=MASK..GW..DNS..DMN
check({v=1},sockO:send(body..toopt()))
execute("sleep 3") -- need to put posix sleep into Lua
check({v=1},sockO:send(body..toopt()))
_ALERT("Looking for DHCPOFFER...\n")
while 1 do
 dgram=check({n=1},sockI:receive())
 if strsub(dgram,1,1)~=BOOTREPLY then
 	fail("DHCPOFFER not found") end
 parse(strsub(dgram,blen+1,-1))
 if glops[MSG]==OFFER then
  break
 end
end
glops[RIP]=strsub(dgram,17,20)
glops[MSG]=REQUEST
check({v=1},sockO:send(body..toopt()))
_ALERT("Looking for DHCPACK...\n")
while 1 do
 dgram=check({n=1},sockI:receive())
 if strsub(dgram,1,1)~=BOOTREPLY then
 	fail("DHCPACK not found") end
 parse(strsub(dgram,blen+1,-1))
 if glops[MSG]==ACK then
  break
 end
end
if glops[RIP] then print("IPADDR="..todots(RIP)) end
if glops[GW] then print("GATEWAY="..todots(GW)) end
if glops[MASK] then print("NETMASK="..todots(MASK)) end
if glops[DNS] then print("DNS_1="..todots(DNS)) end
if glops[DMN] then print("DOMAIN="..glops[DMN]) end
